/*
 *
 *  * Copyright 2020 New Relic Corporation. All rights reserved.
 *  * SPDX-License-Identifier: Apache-2.0
 *
 */

package com.nr.builder;

import com.google.common.collect.Multimap;
import org.gradle.api.GradleException;
import org.reflections.Reflections;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.reflections.serializers.Serializer;

import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.Properties;

public class PropertySerializer implements Serializer {
    @Override
    public File save(Reflections reflections, String filename) {
        Properties props = new Properties();

        Multimap<String, String> typeAnnotations = reflections.getStore().get(TypeAnnotationsScanner.class.getSimpleName());
        typeAnnotations.keySet().forEach(annotationClass -> {
            String annotatedClasses = String.join(",", typeAnnotations.get(annotationClass));
            props.put(annotationClass, annotatedClasses);
        });

        File file = new File(filename);
        try (FileWriter writer = new FileWriter(file, false)) {
            props.store(writer, "Automatically generated by " + getClass().getSimpleName());
        } catch (Throwable t) {
            throw new GradleException("Failed to write " + filename, t);
        }

        return file;
    }

    @Override
    public Reflections read(InputStream inputStream) {
        throw new GradleException("We don't read using this serializer");
    }

    @Override
    public String toString(Reflections reflections) {
        throw new GradleException("Use save() and not toString()");
    }
}
